import type { Router, RouteRecordRaw } from 'vue-router';

import { usePermissionStoreWithOut } from '/@/store/modules/permission';

import { PageEnum } from '/@/enums/pageEnum';
import { useUserStoreWithOut } from '/@/store/modules/user';

import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';

import { RootRoute } from '/@/router/routes';
import { ModalMessage } from '/@/businessComponents/SwMessage/modalMessage';
import { useAppStore } from '/@/store/modules/app';
// const { getOpenPageLoading } = useTransitionSetting();

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const PAPERINSTALL = PageEnum.PAPERINSTALL;
const PAPERINSTALL_INFO = PageEnum.PAPERINSTALL_INFO;
const RESUMEACTION = PageEnum.RESUMEACTION;
const CLOSEACTION = PageEnum.CLOSEACTION;
const REMOVE_METER = PageEnum.REMOVE_METER;
const RESUME_METER = PageEnum.RESUME_METER;
const CLOSE_ACCOUNT = PageEnum.CLOSE_ACCOUNT;
const PAID_RECONC = PageEnum.PAID_RECONC;
const WATEA_METER_VERIFY = PageEnum.WATEA_METER_VERIFY;

const PAPERINSTALL_ALL_INFO = PageEnum.PAPERINSTALL_ALL_INFO;
const PAPERINSTALL_FEE_INFO = PageEnum.PAPERINSTALL_FEE_INFO;
const CHANGEMETER_INDEX = PageEnum.CHANGEMETER_INDEX;
const CHANGEMETER_APPLICATION = PageEnum.CHANGEMETER_APPLICATION;
const PERIODICMETER_DETAIL = PageEnum.PERIODICMETER_DETAIL;
const OPENWATER_INDEX = PageEnum.OPENWATER_INDEX;
const USEWATERNATURECHANGE_INDEX = PageEnum.USEWATERNATURECHANGE_INDEX;

const CAPACITY_INDEX = PageEnum.CAPACITY_INDEX;
const REPLACE_METER = PageEnum.REPLACE_METER;
const ROOT_PATH = RootRoute.path;

const whitePathList: PageEnum[] = [
  LOGIN_PATH,
  PAPERINSTALL,
  PAPERINSTALL_INFO,
  CLOSEACTION,
  RESUMEACTION,
  REMOVE_METER,
  RESUME_METER,
  CLOSE_ACCOUNT,
  PAID_RECONC,
  WATEA_METER_VERIFY,
  PAPERINSTALL_ALL_INFO,
  PAPERINSTALL_FEE_INFO,
  CHANGEMETER_INDEX,
  CHANGEMETER_APPLICATION,
  PERIODICMETER_DETAIL,
  OPENWATER_INDEX,
  USEWATERNATURECHANGE_INDEX,
  CAPACITY_INDEX,
  REPLACE_METER,
];

export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();

  /* 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面 */
  // router.onError((error) => {
  //   const pattern = /Loading chunk (\d)+ failed/g;
  //   const isChunkLoadFailed = error.message.match(pattern);
  //   const targetPath = router.history.pending.fullPath;
  //   console.log(targetPath)
  //   if (isChunkLoadFailed) {
  //     router.replace(targetPath);
  //   }
  // });
  router.onError((error, to, from) => {
    const appStore = useAppStore();
    const { setPageLoading } = appStore;
    const notModule = /Failed to fetch dynamically imported module|Unable to preload CSS for/;
    // const transitionSetting = {
    //   openPageLoading : false
    // }
    // appStore.setProjectConfig({ transitionSetting });
    setPageLoading(false);
    if (notModule.test(error.message)) {
      ModalMessage({
        title: '提示',
        content: '系统已更新,请点击确认后刷新',
        type: 'warning',
        confirm: () => {
          history.pushState({}, '', '/#' + to.path);
          location.reload();
          console.log('刷新页面');
        },
      });
    }
  });

  router.beforeEach(async (to, from, next) => {
    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath);
      return;
    }

    const token = userStore.getToken;

    // Whitelist can be directly entered
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        const isSessionTimeout = userStore.getSessionTimeout;
        try {
          await userStore.afterLoginAction();
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || '/');
            return;
          }
        } catch {}
      }
      next();
      return;
    }

    // token does not exist
    // if (!token) {
    //   // You can access without permission. You need to set the routing meta.ignoreAuth to true
    //   console.log('to', to)
    //   if (to.meta.ignoreAuth) {
    //     next();
    //     return;
    //   }

    //   // redirect login page
    //   const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
    //     path: LOGIN_PATH,
    //     replace: true,
    //   };

    //   if (to.path) {
    //     redirectData.query = {
    //       ...redirectData.query,
    //       redirect: to.path,
    //     };
    //   }
    //   next(redirectData);
    //   return;
    // }

    // Jump to the 404 page after processing the login
    if (
      from.path === LOGIN_PATH &&
      to.name === PAGE_NOT_FOUND_ROUTE.name &&
      to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
    ) {
      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
      return;
    }

    // get userinfo while last fetch time is empty
    if (userStore.getLastUpdateTime === 0) {
      try {
        await userStore.getUserInfoAction();
      } catch (err) {
        next();
        return;
      }
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    const routes = await permissionStore.buildRoutesAction();

    routes.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw);
    });

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);

    permissionStore.setDynamicAddedRoute(true);

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query });
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
